package org.goat.caprabank.client;

import org.goat.caprabank.shared.entity.User;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;

public class LoginPanel extends Composite {
	interface LoginPanelUiBinder extends UiBinder<Widget, LoginPanel> {
	}
	private static LoginPanelUiBinder uiBinder = GWT.create(LoginPanelUiBinder.class);

	private final Caprabank caprabank;

	public LoginPanel(Caprabank caprabank) {
		initWidget(uiBinder.createAndBindUi(this));
		this.caprabank = caprabank;
	}

	@UiField
	TextBox usernameTextBox;

	@UiField
	PasswordTextBox passwordTextBox;

	@UiHandler("loginButton")
	void onClickLogin(ClickEvent e) {
		boolean isValid = Validation.validateNotNull(usernameTextBox, "username") && Validation.validateNotNull(passwordTextBox, "password");
		if (isValid) {
			caprabank.bankService.login(usernameTextBox.getText(), passwordTextBox.getText(), new DefaultCallback<User>() {

				@Override
				public void onSuccess(User result) {
					caprabank.showAccountDetailsPage(result);
				}
			});
		}
	}

	@UiHandler("registerButton")
	void onClickRegister(ClickEvent e) {
		caprabank.showRegistrationPage();
	}

	@UiHandler("passwordTextBox")
	public void onKeyPressPassword(KeyPressEvent event) {
		if (event.getCharCode() == KeyCodes.KEY_ENTER) {
			onClickLogin(null);
		}
	}
}
